﻿using System;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using Wslzy.Auxiliary.Infrastructure.Domains.Repositories;

namespace Wslzy.Auxiliary.Infrastructure
{
    /// <summary>
    /// 查询扩展
    /// </summary>
    public static partial class Extensions
    {
        /// <summary>
        /// 分页，包含排序
        /// </summary>
        /// <typeparam name="TEntity">实体类型</typeparam>
        /// <param name="source">数据源</param>
        /// <param name="pager">分页对象</param>
        public static IQueryable<TEntity> Page<TEntity>(this IQueryable<TEntity> source, IPager pager)
        {
            if (source == null)
                throw new ArgumentNullException(nameof(source));
            if (pager == null)
                throw new ArgumentNullException(nameof(pager));
            if (string.IsNullOrWhiteSpace(pager.Order))
                pager.OrderBy("Id");
            if (pager.TotalCount <= 0)
                pager.TotalCount = source.Count();
            return source.OrderBy(pager.Order).Skip(pager.GetSkipCount()).Take(pager.PageSize);
        }

        /// <summary>
        /// 转换为分页列表，包含排序分页操作
        /// </summary>
        /// <typeparam name="TEntity">实体类型</typeparam>
        /// <param name="source">数据源</param>
        /// <param name="pager">分页对象</param>
        public static PagerList<TEntity> ToPagerList<TEntity>(this IQueryable<TEntity> source, IPager pager)
        {
            if (source == null)
                throw new ArgumentNullException(nameof(source));
            if (pager == null)
                throw new ArgumentNullException(nameof(pager));
            return new PagerList<TEntity>(pager, source.Page(pager).ToList());
        }
    }
}
